package cn.aion.crawlers;

import cn.aion.dao.ProjectVideoDAO;
import cn.aion.dao.VideoDataDAO;
import cn.aion.model.ProjectVideo;
import cn.aion.model.VideoData;
import cn.aion.util.Helper;
import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import cn.wanghaomiao.xpath.model.JXDocument;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 土豆扫描规则
 * Created by 虚空之翼 on 2016/12/14.
 */
@Crawler(name = "tudou", useUnrepeated = false)
public class Tudou extends BaseSeimiCrawler {
    @Autowired
    private ProjectVideoDAO projectVideoDAO;
    @Autowired
    private VideoDataDAO videoDataDAO;

    @Value("${seimiAgentHost}")
    private String seimiAgentHost;
    @Value("${seimiAgentPort}")
    private int seimiAgentPort;
    @Override
    public String seimiAgentHost() { return this.seimiAgentHost; }
    @Override
    public int seimiAgentPort() { return this.seimiAgentPort; }

    @Override
    public String[] startUrls() {
        return new String[]{"http://www.van-cool.com/admin/base/scan"};
    }

    @Override
    public void start(Response response) {
        main();
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void main() {
        logger.info("开启土豆扫描任务");
        try {
            Request seimiAgentReq;
            List<ProjectVideo> list = projectVideoDAO.getVideoAll();
            for (ProjectVideo video : list) {
                String url = video.getTudouUrl();
                if (url != null && !url.isEmpty()) {
                    logger.info("扫描地址：{}", url);
                    push(Request.build(url, "fetchId"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchId(Response response) {
        try {
            String url = response.getRealUrl();
            String [] arr = url.split("/");
            String dataUrl = "http://dataapi.youku.com/getData?jsoncallback=page_play_model_exponentModel__getNum" +
                    "&num=200001&icode="+arr[5];
            push(Request.build(dataUrl, "fetchData"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchData(Response response){
        String url = response.getRealUrl();
        String videoId = url.substring(url.lastIndexOf("=")+1);

        // 根据URL获取视频ID
        ProjectVideo projectVideo = projectVideoDAO.selectOneByTudou(videoId);
        String info = response.getContent();
        String playCountStr= info.substring(info.lastIndexOf(":")+1, info.length()-4);
        logger.info("{} | 播放总数:{}", projectVideo.getTitle(), playCountStr);

        Integer playCount = Integer.parseInt(playCountStr);
        // 计算当日的递增数量
        VideoData preData = videoDataDAO.selectOnePrevious(projectVideo.getId(), 7);
        Integer addCount = playCount;
        if (preData != null) {
            addCount = playCount - preData.getPlayCount();
        }

        // 如果当天已经抓取过数据就更新数据
        VideoData videoData = videoDataDAO.selectOneToday(projectVideo.getId(), 7);
        if (videoData != null) {
            if (playCount != 0) {
                videoData.setPlayCount(playCount);
                videoData.setPlayAdd(addCount);
                videoDataDAO.update(videoData);
            }
        } else {
            VideoData newData = new VideoData();
            newData.setPlayCount(playCount);
            newData.setPlayAdd(addCount);
//            newData.setComments(Integer.parseInt(comment));
            newData.setVideoId(projectVideo.getId());
            newData.setSrcType(7);
            videoDataDAO.save(newData);
        }
        // 更新总数据
        if (playCount != 0) {
            projectVideoDAO.updateTudouVideoCount(projectVideo.getId(), playCount);
            projectVideoDAO.updateTotal(projectVideo.getId());
            projectVideoDAO.updateApplyTotal(projectVideo.getProjectId(), projectVideo.getAnchorId(), Helper.getVideoTotal(projectVideo));
        }
    }
}
